<?php
namespace backend\models;


use yii\base\Model;

class LoginForm extends Model
{
    //定义登录所需的属性
    public $username;
    public $password;
    //保存是否自动登录的属性
    public $rememberMe=false;
    //保存验证码
    public $verifyCode;
    //保存登录方式的信息
    public $loginMethod='1';






    /**
     * @return array
     */
    public function rules()
    {
        return [
            [['username','password','verifyCode'],'required'],
            [['username'],'string', 'length' => [1,50]],
            [['password'],'string','max'=>'100'],
            [['rememberMe'],'boolean'],
            [['loginMethod'],'integer'],
            //给验证吗添加验证规则
            [
                ['verifyCode'],'captcha','captchaAction'=>'manager/captcha'
            ],
//            [['password'],'validatePassword'],
        ];
    }

    /*
     * 添加自定义验证规则,验证属性是否存在
     */
    public function validateExist($attribute,$params){
        //通过用户名称早到对应的用户
        if(Admin::findOne(['username'=>$this->username])){
            //添加错误信息
            $this->addError('username','用户已经存在!');
            return false;
        }
    }
    /**
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'username'=>'用户名／邮箱',
            'password'=>'密码',
            'rememberMe'=>'记住密码',
            'verifyCode'=>'验证码',
        ];
    }

    /**
     * @return bool
     */
    public function LoginCheck(){
        //表单验证
        if(!$this->validate()){
            return false;
        }
        //通过用户名称获取用户信息
        $adminModel = Admin::findOne(['username'=>$this->username])?Admin::findOne(['username'=>$this->username]):Admin::findOne(['email'=>$this->username]);
        //判断用户是否存在
        if(!$adminModel){
            //添加错误信息
            $this->addError('username','用户不存在!');
            return false;
        }

        //判断用户输入的密码是否正确
        if(\Yii::$app->security->validatePassword($this->password,$adminModel->password_hash)){
            //密码验证成功  duration 设置过期时间,来实现用户的自动登录
            $user  = Admin::findIdentity($adminModel->id);
            if(empty($user)){
                $this->addError('username','该用户已失效');
                return false;
            }
            $rs = \Yii::$app->user->login($user,$this->rememberMe ?3600*24*60 : 0);
            //获取当前用户的登录ip
            $adminModel->last_login_ip = \Yii::$app->request->getUserIP();
            //设置最后的登录时间 更新时间
            $adminModel->last_login_time = time();
            $adminModel->updated_at = $adminModel->last_login_time;
            //更新用户信息
            $adminModel->save();
            //返回登录结果1 | 0
            EveryIsOk::setTisiInfo($rs,'登录');
            return $rs;

        }
        $this->addError('password','登录密码不正确');
        return false;

    }


}
